<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <el-card>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="work-order-form"
    >
      <!-- 基础信息 -->
      <el-form-item label="工单标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入工单标题" />
      </el-form-item>

      <el-form-item label="联系人姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入联系人姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="联系地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入联系地址" />
      </el-form-item>

      <el-form-item label="客户选择" prop="customerId">
        <el-select
          v-model="form.customerId"
          placeholder="请选择客户"
          filterable
          :loading="customerLoading"
          clearable
          @clear="clearCustomer"
          @change="handleCustomerChange"
        >
          <el-option
            v-for="customer in filteredCustomers"
            :key="customer.id"
            :label="customer.customerName || customer.name || '未知客户'"
            :value="customer.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="产品选择" prop="productId">
        <el-select
          v-model="form.productId"
          placeholder="请选择产品"
          filterable
          :loading="productLoading"
          clearable
          @clear="clearProduct"
        >
          <el-option
            v-for="product in filteredProducts"
            :key="product.id"
            :label="product.productName || product.name || '未知产品'"
            :value="product.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="工单类型" prop="type">
        <el-select v-model="typeDisplay" placeholder="请选择工单来源">
          <el-option label="客户下单" value="客户下单" />
          <el-option label="系统自建" value="系统自建" />
        </el-select>
      </el-form-item>

      <el-form-item label="经费" prop="money">
        <el-input
          v-model.number="form.money"
          placeholder="请输入经费金额"
          type="number"
          min="0"
          step="0.01"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="工单描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          rows="4"
          placeholder="请详细描述工单内容"
        />
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item label="相关图片">
        <el-upload
          :action="uploadAction"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-remove="handleRemove"
          list-type="picture-card"
          :file-list="fileList"
          :headers="uploadHeaders"
          multiple
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              支持jpg、png格式，最大不超过5MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import {
  getCustomers,
  getCustomerDetail
} from '@/api/customer';
import {
  getProducts,
  getProductDetail
} from '@/api/product';
import {
  addWorkOrder,
  updateWorkOrder,
  getWorkOrderDetail
} from '@/api/workOrder';
import { uploadFile } from '@/api/file';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { onMounted, ref, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const route = useRoute();
const formRef = ref(null);

const props = defineProps({
  message: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['submit-success']);

// 表单数据
const form = ref({
  id: '',
  title: '',
  name: '',
  customerId: '',
  phone: '',
  address: '',
  productId: '',
  type: '',
  description: '',
  images: [],
  money: undefined
});

// 下拉列表数据
const allCustomers = ref([]);
const allProducts = ref([]);
const fileList = ref([]);

// 加载状态
const customerLoading = ref(false);
const productLoading = ref(false);
const submitLoading = ref(false);

// 搜索关键词
const customerSearch = ref('');
const productSearch = ref('');

// 过滤后的客户和产品列表
const filteredCustomers = computed(() => {
  if (!customerSearch.value) {
    return allCustomers.value;
  }
  return allCustomers.value.filter(customer =>
    (customer.customerName || customer.name || '').toLowerCase().includes(customerSearch.value.toLowerCase())
  );
});

const filteredProducts = computed(() => {
  if (!productSearch.value) {
    return allProducts.value;
  }
  return allProducts.value.filter(product =>
    (product.productName || product.name || '').toLowerCase().includes(productSearch.value.toLowerCase())
  );
});

const typeMap = {
  0: '客户下单',
  1: '系统自建'
};

const typeMapReverse = {
  '客户下单': 0,
  '系统自建': 1
};

const typeDisplay = computed({
  get() {
    return typeMap[form.value.type] || form.value.type;
  },
  set(value) {
    const num = typeMapReverse[value];
    if (num !== undefined) {
      form.value.type = num;
    } else {
      form.value.type = value;
    }
  }
});

// 上传相关配置
const uploadAction = computed(() => {
  return '/api/order/order-client/api/file/upload';
});

const uploadHeaders = computed(() => {
  const userStore = useUserStore();
  const token = userStore.userInfo?.userInfoVO?.token;
  return token ? { Authorization: `Bearer ${token}` } : {};
});

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入工单标题', trigger: 'blur' }],
  name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  type: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入工单描述', trigger: 'blur' }],
  money: [
    { required: false, message: '请输入经费金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '经费金额必须大于等于0', trigger: 'blur' }
  ]
};

// 清空客户选择
const clearCustomer = () => {
  form.value.name = '';
  form.value.phone = '';
  form.value.address = '';
};

// 清空产品选择
const clearProduct = () => {
  // 清空产品相关字段（如果有的话）
};

// 处理客户选择变化
const handleCustomerChange = async (customerId) => {
  if (!customerId) {
    form.value.name = '';
    form.value.phone = '';
    form.value.address = '';
    return;
  }

  try {
    const res = await getCustomerDetail(customerId);
    if (res.data) {
      form.value.name = res.data.name || res.data.customerName || '';
      form.value.phone = res.data.phone || res.data.customerPhone || '';
      form.value.address = res.data.address || res.data.customerAddress || '';
    }
  } catch (error) {
    console.error('获取客户详情失败', error);
    ElMessage.error('获取客户详情失败，请检查网络连接');
  }
};

// 图片上传成功处理
const handleUploadSuccess = (response, uploadFile) => {
  console.log('上传响应:', response);
  if (response && response.data) {
    // 如果是完整的 URL
    if (response.data.url) {
      form.value.images.push(response.data.url);
      fileList.value.push({
        name: response.data.name || uploadFile.name,
        url: response.data.url
      });
    }
    // 如果直接返回 URL 字符串
    else if (typeof response.data === 'string') {
      form.value.images.push(response.data);
      fileList.value.push({
        name: uploadFile.name,
        url: response.data
      });
    }
  } else {
    ElMessage.error('图片上传失败');
  }
};

// 图片上传失败处理
const handleUploadError = (error) => {
  console.error('图片上传失败', error);
  ElMessage.error('图片上传失败: ' + (error.message || '未知错误'));
};

// 移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  const index = fileList.value.findIndex(item => item.url === uploadFile.url);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    form.value.images.splice(index, 1);
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitLoading.value = true;

    let res;
    const formData = { ...form.value, des: form.value.description };

    // 处理图片字段
    if (Array.isArray(form.value.images) && form.value.images.length > 0) {
      formData.pic = form.value.images.join(',');
    } else {
      formData.pic = '';
    }

    if (form.value.id) {
      res = await updateWorkOrder(form.value.id, formData);
      ElMessage.success('工单更新成功');
    } else {
      res = await addWorkOrder(formData);
      ElMessage.success('工单创建成功');
    }

    emit('submit-success');
  } catch (error) {
    console.error('提交失败', error);
    ElMessage.error('提交失败，请重试');
  } finally {
    submitLoading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.push('/work-order');
};

// 初始化表单
const initForm = () => {
  form.value = {
    id: '',
    title: '',
    name: '',
    customerId: '',
    phone: '',
    address: '',
    productId: '',
    type: '', // 默认为空
    description: '', // 确保 description 初始为空字符串
    images: [],
    money: undefined
  };
  fileList.value = [];
  customerSearch.value = '';
  productSearch.value = '';
};

// 处理图片数据
const processImages = (images) => {
  if (!images) {
    fileList.value = [];
    form.value.images = [];
    return;
  }

  let imageArray = [];

  // 处理不同的图片数据格式
  if (typeof images === 'string') {
    // 如果是逗号分隔的字符串
    if (images.includes(',')) {
      imageArray = images.split(',').map(url => url.trim()).filter(Boolean);
    } else {
      // 单个URL
      imageArray = [images];
    }
  } else if (Array.isArray(images)) {
    // 如果已经是数组
    imageArray = images.filter(Boolean);
  }

  // 设置 fileList 和 form.images
  fileList.value = imageArray.map((url, index) => ({
    name: `image_${index + 1}`,
    url: url
  }));

  form.value.images = [...imageArray];
};

// 加载工单详情
const loadWorkOrderDetail = async (id) => {
  try {
    const res = await getWorkOrderDetail(id);
    if (res.data) {
      form.value = {
        ...res.data,
        description: res.data.des || '' // 显式映射 des -> description
      };

      // 初始化图片列表，处理 pic 字段
      processImages(res.data.pic || res.data.images);

      // 主动加载客户和产品信息以显示名称
      if (res.data.customerId) {
        await loadCustomerById(res.data.customerId);
      }
      if (res.data.productId) {
        await loadProductById(res.data.productId);
      }
    }
  } catch (error) {
    console.error('获取工单详情失败', error);
    ElMessage.error('获取工单详情失败');
  }
};

// 根据 ID 加载客户并添加到 customerList
const loadCustomerById = async (id) => {
  try {
    const res = await getCustomerDetail(id);
    if (res.data) {
      const customer = res.data;
      const exists = allCustomers.value.some(c => c.id === id);
      if (!exists) {
        allCustomers.value.push({
          id: customer.id,
          customerName: customer.customerName || customer.name,
          name: customer.name,
          phone: customer.phone,
          address: customer.address
        });
      }
    }
  } catch (error) {
    console.error('加载客户失败', error);
  }
};

// 根据 ID 加载产品并添加到 productList
const loadProductById = async (id) => {
  try {
    const res = await getProductDetail(id);
    if (res.data) {
      const product = res.data;
      const exists = allProducts.value.some(p => p.id === id);
      if (!exists) {
        allProducts.value.push({
          id: product.id,
          productName: product.productName || product.name,
          name: product.name
        });
      }
    }
  } catch (error) {
    console.error('加载产品失败', error);
  }
};

// 加载所有客户
const loadAllCustomers = async () => {
  try {
    customerLoading.value = true;
    const res = await getCustomers({ pageSize: 1000 });
    if (res.data.records) {
      allCustomers.value = res.data.records;
    } else if (res.data.list) {
      allCustomers.value = res.data.list;
    } else {
      allCustomers.value = res.data || [];
    }
  } catch (error) {
    console.error('获取客户列表失败', error);
    ElMessage.error('获取客户列表失败');
  } finally {
    customerLoading.value = false;
  }
};

// 加载所有产品
const loadAllProducts = async () => {
  try {
    productLoading.value = true;
    const res = await getProducts({ pageSize: 1000 });
    if (res.data.records) {
      allProducts.value = res.data.records;
    } else if (res.data.list) {
      allProducts.value = res.data.list;
    } else {
      allProducts.value = res.data || [];
    }
  } catch (error) {
    console.error('获取产品列表失败', error);
    ElMessage.error('获取产品列表失败');
  } finally {
    productLoading.value = false;
  }
};

// 监听传入的 message 变化
watch(
  () => props.message,
  (newVal) => {
    if (newVal && newVal.id) {
      form.value = {
        ...newVal,
        description: newVal.des || ''
      };

      // 初始化图片列表
      processImages(newVal.pic || newVal.images);

      // 主动加载客户和产品信息以显示名称
      if (newVal.customerId) {
        loadCustomerById(newVal.customerId);
      }
      if (newVal.productId) {
        loadProductById(newVal.productId);
      }
    } else {
      // 如果没有传入数据，初始化为空表单
      initForm();
    }
  },
  { immediate: true }
);

// 页面初始化
onMounted(async () => {
  const workOrderId = route.params.id;

  // 加载所有客户和产品
  await Promise.all([
    loadAllCustomers(),
    loadAllProducts()
  ]);

  if (workOrderId) {
    await loadWorkOrderDetail(workOrderId);
  } else if (!props.message || !props.message.id) {
    initForm();
  }
});
</script>

<style scoped>
.work-order-form {
  max-width: 600px;
  margin: 0 auto;
}
</style>
